package com.yisu.expressway.onedollar.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.adapter.OrderShowPicGridListAdapter;
import com.yisu.expressway.onedollar.widget.DownUpPopupWindow;
import com.yisu.expressway.onedollar.widget.NoScrollGridView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.utils.BitmapUtil;
import com.yisu.expressway.utils.HBLog;
import com.yisu.expressway.utils.QiniuUploadManager;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Created by shijunfeng on 2016/12/16.
 */
public class OrderShowBuildActivity extends BasicActivity
        implements AndroidImagePicker.OnImagePickCompleteListener,
        OrderShowPicGridListAdapter.PicItemClickListener {
    public static final int REQUEST_CODE_NORMAL = 4;
    private static final String EXTRA_KEY_BARCODE = "extra_key_barcode";
    private static final String EXTRA_KEY_ORDER_ID = "extra_key_order_id";
    private static final String EXTRA_KEY_GOODS_NAME = "extra_key_goods_name";
    private static final String EXTRA_KEY_PERIOD_NUM = "extra_key_period_num";
    private static final String EXTRA_KEY_GOODS_PIC = "extra_key_goods_pic";
    private static final String TAG = OrderShowBuildActivity.class.getSimpleName();
    private static final int PHOTO_REQUEST_CAMERA = 200;// 拍照
    private static final String EXTRA_KEY_REQUEST = "extra_key_request";
    private final int ORDER_SHOW_PIC_MAX = 3;
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.iv_goods_cover)
    protected ImageView mGoodsCoverIv;
    @Bind(R.id.tv_goods_name)
    protected TextView mGoodsNameTv;
    @Bind(R.id.tv_periodsnum)
    protected TextView mPeriodsNumTv;
    @Bind(R.id.et_evaluate)
    protected EditText mEvaluateEt;
    @Bind(R.id.gridview)
    protected NoScrollGridView mGridView;
    private List<ImageItem> mImageList = new ArrayList<>();
    private String mEvaluateConent;
    private ImageItem mImgItemCamera;
    private boolean bAnonymous = false;
    private OrderShowPicGridListAdapter mAdapter;
    private List<String> mUploadUrlList = new ArrayList<>();
    private long mOrderId;
    private long mBarcode;
    private String mGoodsName;
    private long mPeriodsNum;
    private String mGoodsPic;
    private DownUpPopupWindow mDownUpPopupWindow;

    public static void launch(Activity context, int requestCode, long recordId, long barCode,
                              String goodsName, long periodsNum, String goodsPic) {
        Intent intent = new Intent(context, OrderShowBuildActivity.class);
        intent.putExtra(EXTRA_KEY_ORDER_ID, recordId);
        intent.putExtra(EXTRA_KEY_BARCODE, barCode);
        intent.putExtra(EXTRA_KEY_GOODS_NAME, goodsName);
        intent.putExtra(EXTRA_KEY_PERIOD_NUM, periodsNum);
        intent.putExtra(EXTRA_KEY_GOODS_PIC, goodsPic);
        context.startActivityForResult(intent,requestCode);
    }

    @OnCheckedChanged(R.id.checkbox)
    protected void onCheckChanged(boolean check) {
        bAnonymous = check;
    }

    @OnClick({ R.id.tv_submit })
    protected void onEveluateClick(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                submitEveluateContent();
                break;
            default:
                break;
        }

    }

    private void submitEveluateContent() {
        mEvaluateConent = mEvaluateEt.getText().toString();
        if (TextUtils.isEmpty(mEvaluateConent) && mImageList.isEmpty()) {
            ToastUtil.showMessage(this, "请输入内容");
            return;
        }
        if (mImageList.isEmpty()){
            upload2BusinessServer();
        }else {
            upload2FileServer();
        }

    }

    private void upload2BusinessServer() {
        Map<String, Object> params = new HashMap();
        params.put("orderId", mOrderId);
        params.put("barcode", mBarcode);
        params.put("evaluateContent", mEvaluateConent);
        params.put("isAnonymous", bAnonymous ? 1 : 0);
        params.put("evaluatePic",
                mUploadUrlList.isEmpty() ? "" : StringUtil.join(mUploadUrlList.toArray(), ","));
        ApiClientHelper.postApi(ApiSetting.orderShow(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                dismissLoading();
                if (!result.success) {
                    ToastUtil.displayShortToastMsg(OrderShowBuildActivity.this,
                            TextUtils.isEmpty(result.getMsg()) ? "上传失败" : result.getMsg());

                    return;
                }
                ToastUtil.displayShortToastMsg(OrderShowBuildActivity.this,
                        TextUtils.isEmpty(result.getMsg()) ? "上传成功" : result.getMsg());
                setResult(RESULT_OK);
                finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(OrderShowBuildActivity.this,
                        TextUtils.isEmpty(volleyError.getMessage()) ? "上传失败"
                                : volleyError.getMessage());
                dismissLoading();
            }
        }, this);
    }

    private void upload2FileServer() {
        if (mImageList.isEmpty()) {
            return;
        }
        mUploadUrlList.clear();
        for (ImageItem imageItem : mImageList) {
            if (TextUtils.isEmpty(imageItem.path)) {
                continue;
            }
            String filePath = BitmapUtil.scalePictureBitmapForAvatar(imageItem.path);//压缩图片
            if (StringUtil.isNullOrEmpty(filePath)) {
                filePath = imageItem.path;
            }

            showLoading();
            QiniuUploadManager.getInstance().getTokenAndUploadHeadImg(filePath,
                    new QiniuUploadManager.UpLoadListener() {
                        @Override
                        public void uploadSuccess(String url, int w, int h) {
                            mUploadUrlList.add(url);
                            if (mUploadUrlList.size() == mImageList.size()) {
                                upload2BusinessServer();
                            }
                        }

                        @Override
                        public void uploadFail(String error) {
                            ToastUtil.displayShortToastMsg(OrderShowBuildActivity.this,
                                    TextUtils.isEmpty(error) ? "上传失败" : error);
                            dismissLoading();
                        }

                        @Override
                        public void onGetToken(String token) {

                        }

                        @Override
                        public void onGetTokenApiFail(String error) {
                            ToastUtil.displayLongToastMsg(OrderShowBuildActivity.this, error);
                            dismissLoading();
                        }

                        @Override
                        public void onGetTokenNetworkFail(VolleyError volleyError) {
                            ToastUtil.displayShortToastMsg(OrderShowBuildActivity.this, "网络不给力");
                            dismissLoading();
                        }
                    });
        }

    }

    private void pickPicFromAlbum() {
        AndroidImagePicker instance = AndroidImagePicker.getInstance();
        instance.setSelectLimit(ORDER_SHOW_PIC_MAX - mImageList.size());
        instance.pickMulti(this, false, this);
    }

    private void pickPicFromCamera() {
        try {
            AndroidImagePicker.getInstance().takePicture(this, PHOTO_REQUEST_CAMERA);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTO_REQUEST_CAMERA:
                String currentPhotoPath = AndroidImagePicker.getInstance().getCurrentPhotoPath();
                HBLog.d(TAG, "onActivityResult" + currentPhotoPath);
                mImageList.add(new ImageItem(currentPhotoPath, currentPhotoPath, -1));
                List<ImageItem> temp = new ArrayList<>();
                temp.addAll(mImageList);
                temp.add(mImgItemCamera);
                mAdapter.setData(temp);
                mAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_onedollar_order_show_build;
    }

    @Override
    protected void initPresenter() {
    }

    @Override
    protected void releasePresenter() {

    }

    @Override
    protected void getIntentData(Intent intent) {
        long orderid = intent.getLongExtra(EXTRA_KEY_ORDER_ID, -1);
        long barcode = intent.getLongExtra(EXTRA_KEY_BARCODE, -1);
        if (orderid <= 0 || barcode <= 0) {
            finish();
            return;
        }
        mOrderId = orderid;
        mBarcode = barcode;
        mGoodsName = intent.getStringExtra(EXTRA_KEY_GOODS_NAME);
        mPeriodsNum = intent.getLongExtra(EXTRA_KEY_PERIOD_NUM, -1);
        mGoodsPic = intent.getStringExtra(EXTRA_KEY_GOODS_PIC);
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        mImgItemCamera = new ImageItem(OrderShowPicGridListAdapter.CAMER_URL, "", 0);
        List<ImageItem> picList = new ArrayList<>();
        picList.addAll(mImageList);
        picList.add(mImgItemCamera);
        mAdapter = new OrderShowPicGridListAdapter(this, picList, this);
        mAdapter.setCountLimit(ORDER_SHOW_PIC_MAX + 1);
        mGridView.setAdapter(mAdapter);
        if (!TextUtils.isEmpty(mGoodsName)) {
            mGoodsNameTv.setText(mGoodsName);
        }
        if (mPeriodsNum > 0) {
            String format = String.format(getString(R.string.one_dollar_periods_num), mPeriodsNum);
            mPeriodsNumTv.setText(format);
        }
        if (!TextUtils.isEmpty(mGoodsPic)) {
            String[] split = mGoodsPic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(getApplicationContext()).load(picShow).asBitmap()
                        .placeholder(R.drawable.pic_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).fitCenter()
                        .animate(R.anim.fade_in_image).into(mGoodsCoverIv);
            }
        } else {
            mGoodsCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }

    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finishSelf(true);
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void onImagePickComplete(List<ImageItem> items) {
        if (items == null || items.isEmpty()) {
            return;
        }
        mImageList.addAll(items);
        List<ImageItem> temp = new ArrayList<>();
        temp.addAll(mImageList);
        temp.add(mImgItemCamera);
        mAdapter.setData(temp);
        mAdapter.notifyDataSetChanged();
        HBLog.d(TAG, "onActivityResult");
    }

	@Override
	public void onPicItemClick(String picUrl, int position) {

	}

    @Override
    public void onPicItemLongClick(final String picUrl, final int position) {
        if (TextUtils.isEmpty(picUrl)) {
            return;
        }
        if (mImageList == null || mImageList.isEmpty()) {
            return;
        }
        final MultiButtonDialog dialog = new MultiButtonDialog(this);
        dialog.show();
        dialog.setContentText("确认删除？");
        dialog.setButtonColor(R.color.oneDollarCommon);
        dialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
	        @Override
	        public void onPositiveClick(String inputContent) {
		        mImageList.remove(position);
		        List<ImageItem> temp = new ArrayList<>();
		        temp.addAll(mImageList);
		        temp.add(mImgItemCamera);
		        mAdapter.setData(temp);
		        mAdapter.notifyDataSetChanged();
		        dialog.dismiss();
	        }

        });

    }

    @Override
    public void onCameraItemClick() {
        showPopDlg();
    }

    private void showPopDlg() {
        if (mDownUpPopupWindow == null) {
            View view = getLayoutInflater().inflate(R.layout.popwindow_down_up_ordershow, null);
            mDownUpPopupWindow = new DownUpPopupWindow(this, view);
            view.findViewById(R.id.tv_photograph).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pickPicFromCamera();
                    dismissPopDlg();
                }
            });
            view.findViewById(R.id.tv_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pickPicFromAlbum();
                    dismissPopDlg();
                }
            });
            view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissPopDlg();
                }
            });
        }
        mDownUpPopupWindow.showAtLocation(mTitleView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                0);

    }

    public void dismissPopDlg() {
        if (mDownUpPopupWindow != null && mDownUpPopupWindow.isShowing()) {
            mDownUpPopupWindow.dismiss();
            mDownUpPopupWindow = null;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishSelf(true);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void finishSelf(boolean bShowDlg) {
        if (!bShowDlg) {
            finish();
            return;
        }
        if (!TextUtils.isEmpty(mEvaluateEt.getText())
                || (mImageList != null && !mImageList.isEmpty())) {
            showQuitWarningDlg();
        } else {
            finish();
        }
    }

    private void showQuitWarningDlg() {
        final MultiButtonDialog multiButtonDialog = new MultiButtonDialog(
                OrderShowBuildActivity.this);
        multiButtonDialog.show();
        multiButtonDialog.setContentText(R.string.one_dollar_order_status_quit_warning);
        multiButtonDialog.setButtonColor(R.color.oneDollarCommon);
        multiButtonDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
            @Override
            public void onPositiveClick(String inputContent) {
                multiButtonDialog.dismiss();
                finish();
            }
        });
        multiButtonDialog.setNegativeClickListener(new MultiButtonDialog.NegativeClickListener() {
            @Override
            public void onNegativeClick(String inputContent) {
                multiButtonDialog.dismiss();
            }
        });
    }
}
